import React, { Component } from "react";
import { Table, Form, Input, Button, Popconfirm, Row, Col, Radio, Select, DatePicker, Modal } from "antd";
import moment from "moment";
import Content from "../../components/Content/Content";

const { Item } = Form;
const { TextArea } = Input;
const { Option } = Select;

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} 不能为空.`,
              
            },
          ],
          initialValue: record[dataIndex],
        })(<Input className='InputValue' ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"

        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: 'ID',
        dataIndex: 'id', 
        editable: false,
      },
      {
        title: '培养基编号',
        dataIndex: 'medium_sn', 
        editable: true,
      },
      {
        title: '培养基名称',
        dataIndex: 'medium_name',
        editable: true,
      },
      {
        title: '培养基成分',
        dataIndex: 'mediumcf',
        editable: true,
      },
      {
        title: '培养基灭菌条件',
        dataIndex: 'medium_tj',
        editable: true,
      },
      {
        title: '培养基类型',
        dataIndex: 'medium_type',
        editable: true,
      },
      {
        title: '添加时间',
        dataIndex: 'add_time',
        editable: true,
      },
      {
        title: '操作',
        dataIndex: 'operation',

        render: (text, record) =>
          this.state.dataSource.length >= 1 ? (
            <Popconfirm title="确认删除吗?" onConfirm={() => this.handleDelete(record.id)}>
              <a>删除</a>
            </Popconfirm>
            
          ) : null,
      },
    ];
 
  }

  state = {
    options: [],

    newData: {},

    dataSource: [],
    
    count: 0,
    loading: true,
    pageNum: 1,
    pageSize: 100
  };

  loadData = (current, query) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    if( !current ) current = 1;
      
    let medium_sn = this.state.newData.medium_sn;
    let medium_name = this.state.newData.medium_name;
    let medium_type = this.state.newData.medium_type;
    let add_time = this.state.newData.add_time;
    let mediumcf = this.state.newData.mediumcf;

    if( !medium_sn || medium_sn == 'undefined' ) {medium_sn = '';}
    if( !medium_name || medium_name == 'undefined' ) {medium_name = '';}
    if( !medium_type || medium_type == 'undefined' ) {medium_type = '';}
    if( !add_time || add_time == 'undefined' ) {add_time = '';}
    if( !mediumcf || mediumcf == 'undefined' ) {mediumcf = '';}

    const url = global.api.medium + "?medium_sn=" + medium_sn + '&medium_name=' + medium_name + '&medium_type=' + medium_type + '&add_time=' + add_time + '&mediumcf=' + mediumcf;
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count, loading: false})
    })
    .catch(err => {
      Modal.error({
        content: '网络异常!',
      });
    }) 

  }

  loadOptions = (current = 1) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    const url = global.api.getMediumCF + '?_t=' + (new Date()).valueOf();
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize})
    .then(res => {
      this.setState({options: res, newData: {}})
    })
    .catch(err => {
      Modal.error({
        content: '网络异常!',
      });
    }) 

  }

  componentDidMount() {
    
    this.loadOptions(1);
    this.loadData(1);

  }

  onShowSizeChange = (current, pageSize) => {
    this.loadData(this.state.acqType, current, pageSize);
    this.setState({
        pageSize: pageSize
    })
  }

  paginationProps = {
    showSizeChanger: true,//设置每页显示数据条数
    showQuickJumper: false,
    showTotal: () => `共${this.state.count}条`,
    pageSize: this.state.pageSize,
    total: this.state.count,  //数据的总的条数
    onChange: (current) => this.loadData(current), //点击当前页码
    onShowSizeChange: (current, pageSize) => {//设置每页显示数据条数，current表示当前页码，pageSize表示每页展示数据条数
        console.log(pageSize);
        this.onShowSizeChange(current, pageSize)
    }
  }

  handleDelete = id => {
    // 删除数据
    const url = global.api.medium + id + '/';
    return global.deletedata.del(url)
    .then(res => {
      this.loadData(1);

      Modal.success({
        content: '删除成功'
      })
    })
    .catch(err => {
      Modal.error({
        content: '删除出错'
      })
    })
    
  };


  handleSave = row => {

    // 更新数据
    const url = global.api.medium + row.id + '/';
    return global.updatedata.put(url, row)
    .then(res => {
      this.loadData(1); 

      Modal.success({
        content: '保存成功'
      })
    })
    .catch(err => {
      Modal.error({
        content: '保存出错'
      })
    })
    
  };

  render() {
    const { dataSource } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      }
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    
    let dateFormat = 'YYYY-MM-DD';

    return (
      
      <Content>
        <div className="filtrate">
          <Form {...formItemLayout} colon={false}>

            <Item label="培养基编号">
              <Input id="medium_sn" onChange={e => this.state.newData.medium_sn = e.target.value} />
            </Item>
            <Item label="培养基名称">
              <Input id="medium_name" onChange={e => this.state.newData.medium_name = e.target.value} />
            </Item>
            <Item label="培养基成分">
              <Select 
                style={{ width: 180 }}
                onChange={value => this.state.newData.mediumcf = value.join(',') } 
                placeholder="请选择成分"

                mode="tags"
                showArrow={true}

              >
                    { this.state.options && this.state.options.map((item)=>
                        <Option value={item.name}>{item.name}</Option>
                    )}
              </Select>  
            </Item>
            <Item label="培养基条件">
              <Input id="medium_tj" onChange={e => this.state.newData.medium_tj = e.target.value} />
            </Item>
            <Item label="培养基类型">
              <Select
                
                id="medium_type"
                style={{ width: "100%" }}
                onChange={value => this.state.newData.medium_type = value }             
                showArrow={true}
              >
                <Option value="cj">通用</Option>
                <Option value="zj">重要</Option>
                <Option value="gj">特殊</Option>
              </Select>
            </Item>

            <Item label="添加时间">
              <DatePicker onChange={(a,b) => this.state.newData.add_time = b} format={dateFormat} id="add_time" />
            </Item>
            <Item wrapperCol={{ span: 6, offset: 4 }}>
              <Row guuter={16}>
                <Col span={6}>
                  <Button type="primary" onClick={() => this.loadData(1)}>
                    查询
                  </Button>
                </Col>
              </Row>
            </Item>
          </Form>
        </div>
        <div style={{ marginTop: '24px', display: 'none' }}>
          <Button type="primary" style={{ marginLeft: '24px' }}>
            保存
          </Button>
        </div>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          pagination={this.paginationProps}
          columns={columns}
        />
      </Content>
    );
  }
}

const ActivityScreeningPrimary = Form.create()(EditableTable);
export default ActivityScreeningPrimary;
